﻿using Liuliu.ScriptEngine;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;

namespace GmPrizedrawTool
{
    /// <summary>
    /// 击杀BOSS提醒
    /// </summary>
    internal class KillBoss
    {
        public static string LastBossName = "";//最后被检测到死亡的BOSS名字
        public static DataTable BossCsvDt = new DataTable();//Boss列表
        public static List<GameBossModel> BossList = new List<GameBossModel>();//Boss列表
        public static Dictionary<int, BossRefreshYG> DicBossRefreshYg = new Dictionary<int, BossRefreshYG>();
        public static void ListionMessageBox(int Hwnd)
        {
            DmPlugin dm = Program.dm;
            AddLog("检测Boss被击杀监控日志");
            LoadBossInfo();
            long timer = 0;//最大值5分钟(300000)，方便预告喊话减少耗时
            bool disConnection = false;
            while (true)
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                //判断是否登录页面报错
                int aX = 0, aY = 0;
                int dm_ret = dm.FindPic(451, 415, 586, 456, "Config\\loginerr.bmp", "000000", 0.8, 0, out aX, out aY);
                if (dm_ret != -1)
                {
                    dm.MoveToClick(495, 443);
                    Thread.Sleep(50);
                    disConnection = true;
                    break;
                }
                //移动到消息框，双击最新消息
                dm.MoveTo(157, 706);
                dm.LeftDoubleClick();
                Thread.Sleep(10);

                //移动光标之末尾
                dm.KeyPress(35);//End
                Thread.Sleep(10);
                //模拟全选
                Hwnds.keybd_event(16, 0, 0, 0);
                Thread.Sleep(30);
                Hwnds.PostMessage(Hwnd, Hwnds.WM_KEYDOWN, 36, 0);
                Thread.Sleep(30);
                Hwnds.keybd_event(16, 0, 2, 0);
                Thread.Sleep(30);

                //复制
                Hwnds.keybd_event(17, 0, 0, 0);
                Thread.Sleep(30);
                Hwnds.PostMessage(Hwnd, Hwnds.WM_KEYDOWN, 67, 0);
                Thread.Sleep(30);
                Hwnds.keybd_event(17, 0, 2, 0);
                Thread.Sleep(30);

                dm.KeyPress(46);

                try
                {
                    string ClipboardVal = dm.GetClipboard();

                    if (!string.IsNullOrEmpty(ClipboardVal) && ClipboardVal.Contains("杀") && ClipboardVal.Contains("BOSS["))
                    {
                        string pattern = @"BOSS\[([^\]]+)\]";
                        Regex regex = new Regex(pattern);
                        Match match = regex.Match(ClipboardVal);
                        if (match.Success)
                        {
                            #region 名字去掉等级-弃用
                            //pattern = @"[\u4e00-\u9fa5]+";
                            //regex = new Regex(pattern);
                            //match = regex.Match(match.Groups[1].Value); 
                            #endregion
                            string bossName = match.Groups[1].Value;
                            if (bossName != LastBossName && !bossName.Contains("幸运财神") && !bossName.Contains("游荡英灵"))
                            {
                                DateTimeOffset KillTime = DateTimeOffset.UtcNow;
                                Console.WriteLine($"检测到BOSS被击杀。BOSS的名字是: {bossName},时间:{DateTime.Now.ToString("MM-dd HH:mm:ss")}");
                                AddLog($"检测到BOSS被击杀。BOSS的名字是: {bossName},时间:{DateTime.Now.ToString("MM-dd HH:mm:ss")}");
                                //调用API上传Boss被击杀信息
                                GameBossModel model = GetModelByBossName(bossName);
                                if (model.RefreshType == "xitong")
                                {
                                    SendBossKilledInfo(model.ID, KillTime, 0);
                                }
                                else
                                {
                                    SendBossKilledInfo(model.ID, KillTime, 0);
                                }
                                LastBossName = bossName;
                                //获取该BOSS的下次刷新时间
                                DateTime nextRefreshTime = NextRefreshTime(model);
                                if (DicBossRefreshYg != null && DicBossRefreshYg.ContainsKey(model.ID))
                                {
                                    DicBossRefreshYg[model.ID] = new BossRefreshYG { HaveNotice = false, NextRefreshTime = nextRefreshTime, YgNotice = model.YuGaoNotice.Replace("\"", "") };
                                }
                                else
                                {
                                    DicBossRefreshYg.Add(model.ID, new BossRefreshYG { HaveNotice = false, NextRefreshTime = nextRefreshTime, YgNotice = model.YuGaoNotice.Replace("\"", "") });
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("未匹配到BOSS名字。");
                        }
                        Thread.Sleep(100);
                    }

                    //设置为每分钟执行一次
                    if (timer >= 60000 && DicBossRefreshYg != null && DicBossRefreshYg.Values.Any(p => p.NextRefreshTime < DateTime.Now.AddMinutes(6)))
                    {
                        if (DicBossRefreshYg.Keys.Count > 0)
                        {
                            foreach (int bossId in DicBossRefreshYg.Keys)
                            {
                                BossRefreshYG yG = DicBossRefreshYg[bossId];
                                DateTime nowTime = DateTime.Now;
                                if (yG.NextRefreshTime < nowTime)
                                {
                                    // 移除该Boss信息
                                    DicBossRefreshYg.Remove(bossId);
                                    continue;
                                }
                                if (!yG.HaveNotice && (yG.NextRefreshTime - nowTime).TotalMinutes > 5 && (yG.NextRefreshTime - nowTime).TotalMinutes < 6)
                                {
                                    //发送预告喊话
                                    Console.WriteLine($"{yG.YgNotice}时间:{DateTime.Now.ToString("MM - dd HH: mm:ss")}");
                                    RandomReward.SendOneNotice(yG.YgNotice);
                                    //移除该Boss信息
                                    DicBossRefreshYg.Remove(bossId);
                                }
                            }
                        }
                        timer = 0;
                    }
                }
                catch (Exception ex)
                {
                    // 处理异常
                    Console.WriteLine($"操作出现异常: {ex.Message}");
                }
                Thread.Sleep(200);
                stopwatch.Stop();
                timer += stopwatch.ElapsedMilliseconds;
            }
            //检测到掉线断开连接，重连
            if (disConnection)
            {
                LoginGame.StartLogin(Hwnd, 1);
            }
        }

        /// <summary>
        /// 加载Boss信息
        /// </summary>
        public static void LoadBossInfo()
        {
            string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config\\allboss.csv"); 
            if (File.Exists(filePath))
            {
                BossCsvDt = CsvHelper.OpenCSV(filePath, 0, 0, 0, 0, false);
                if (BossCsvDt != null && BossCsvDt.Rows.Count > 0)
                {
                    for (int i = 0; i < BossCsvDt.Rows.Count; i++)
                    {
                        GameBossModel model = new GameBossModel();
                        DataRow row = BossCsvDt.Rows[i];
                        if (row["COL7"].ToString() == "xitong")
                        {
                            model.ID = Convert.ToInt32(row["COL0"]);
                            model.Name = row["COL1"].ToString();
                            model.Avator = row["COL2"].ToString();
                            model.Point = row["COL3"].ToString();
                            model.TimeSpan = Convert.ToInt32(row["COL4"]);
                            model.StartTime = row["COL5"].ToString();
                            model.EndTime = row["COL6"].ToString();
                            model.RefreshType = row["COL7"].ToString();
                            model.RefreshNotice = row["COL8"].ToString();
                            model.YuGaoNotice = row["COL9"].ToString();
                            string LevelStr = row["COL10"].ToString();
                            if (LevelStr.Contains("-")) {
                                string[] levelArr = LevelStr.Split('-');
                                model.chrLevL = Convert.ToInt32(levelArr[0]);
                                model.chrLevH = Convert.ToInt32(levelArr[1]);
                            }
                            model.mapName = row["COL11"].ToString();
                            model.refreshGL = Convert.ToInt32(row["COL12"]);
                            BossList.Add(model);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 通过Boss名字获取Boss信息
        /// </summary>
        /// <param name="BossName">Boss名字</param>
        /// <returns></returns>
        public static GameBossModel GetModelByBossName(string BossName)
        {
            return BossList.FirstOrDefault(p => p.Name.Contains(BossName));
        }

        /// <summary>
        /// 上传Boss被杀掉记录
        /// </summary>
        /// <param name="Id">Boss ID</param>
        /// <param name="timeSpan">刷新间隔</param>
        /// <returns></returns>
        public static bool SendBossKilledInfo(int Id,DateTimeOffset KillTime, int timeSpan) {
            string NoticeApiUrl = $"{Program.ApiAddress}Api/Interface/AddBossKilled";
            long unixTimestamp = KillTime.ToUnixTimeSeconds();
            string FormData = $"Id={Id}&KillTime={unixTimestamp}&ts={timeSpan}";
            string ReturnVal = CommonFun.HttpPostRaw(NoticeApiUrl, FormData);
            if (ReturnVal.Contains("200"))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取指定BOSS的下次刷新时间
        /// </summary>
        /// <param name="model">当前Boss信息</param>
        /// <returns></returns>
        public static DateTime NextRefreshTime(GameBossModel model)
        {
            DateTime nowTime = DateTime.Now;
            if (model.RefreshType == "xitong" && !string.IsNullOrEmpty(model.StartTime))
            {
                int startHour = Convert.ToInt32(model.StartTime);
                DateTime startRefreshTime = Convert.ToDateTime($"{nowTime.Year}-{nowTime.Month}-{nowTime.Day} {startHour}:00:00");
                return startRefreshTime.AddDays(1);
            }
            else { 
                return nowTime.AddSeconds(model.TimeSpan);
            }
        }

        //记录本地日志
        public static void AddLog(string logmsg)
        {
            string sFilePath = AppDomain.CurrentDomain.BaseDirectory + "logs";
            string sFileName = "killboss_" + DateTime.Now.ToString("dd") + ".log";
            sFileName = sFilePath + "\\" + sFileName; //文件的绝对路径
            if (!Directory.Exists(sFilePath))//验证路径是否存在
            {
                Directory.CreateDirectory(sFilePath);
            }
            using (StreamWriter sw = new StreamWriter(sFileName, true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + "   ---   " + logmsg);
                sw.Close();
            }
        }
    }

    /// <summary>
    /// Boss实体类
    /// </summary>
    public class GameBossModel
    {
        /// <summary>
        /// BOSS ID
        /// </summary>
        public int ID { get; set; }
        /// <summary>
        /// BOSS 名字
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// BOSS 头像
        /// </summary>
        public string Avator { get; set; }
        /// <summary>
        /// BOSS 坐标
        /// </summary>
        public string Point { get; set; }
        /// <summary>
        /// 刷新间隔
        /// </summary>
        public int TimeSpan { get; set; }
        /// <summary>
        /// 开始时间
        /// </summary>
        public string StartTime { get; set; }
        /// <summary>
        /// 结束时间
        /// </summary>
        public string EndTime { get; set; }
        /// <summary>
        /// 刷新方式
        /// </summary>
        public string RefreshType { get; set; }
        /// <summary>
        /// 刷新喊话
        /// </summary>
        public string RefreshNotice { get; set; }
        /// <summary>
        /// 预告喊话
        /// </summary>
        public string YuGaoNotice { get; set; }
        /// <summary>
        /// 适配用户最低等级
        /// </summary>
        public int chrLevL { get; set; }
        /// <summary>
        /// 适配用户最高等级
        /// </summary>
        public int chrLevH { get; set; }
        /// <summary>
        /// 地图
        /// </summary>
        public string mapName { get; set; }
        /// <summary>
        /// 刷新概率
        /// </summary>
        public int refreshGL { get; set; }
    }

    /// <summary>
    /// Boss 刷新预告实体
    /// </summary>
    public class BossRefreshYG
    {
        /// <summary>
        /// 是否已预告刷新
        /// </summary>
        public bool HaveNotice { get; set; }
        /// <summary>
        /// 下次刷新时间
        /// </summary>
        public DateTime NextRefreshTime { get; set; }
        /// <summary>
        /// 预告喊话内容
        /// </summary>
        public string YgNotice { get; set; }
    }
}
